package com.sdx.console.ncode.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.utils.CodeUtils;
import com.sdx.console.utils.EDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.ncode.entity.*;
import com.sdx.console.ncode.service.*;
import com.sdx.console.ncode.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * N码批次管理 接口
 */
@RequestMapping("/ncode/ncodebatch")
@Controller
public class RightNcodeBatchController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(RightNcodeBatchController.class);
    private static final String MODEL = "/ncode/ncodebatch";

    @Resource
    private SQLManager sqlManager;

    @Resource
	private RightNcodeBatchService ncodebatchService;

    @Resource
    private RightNcodeService rightNcodeService;

    @Resource
    private BaseDataService baseDataService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        RightRole role = new RightRole() ;
        CoreUser user = getLoginUser(request);
        role.setRoleType(1);
        role.setTenantId(user.getTenantId());
        List<RightRole> roleList = sqlManager.template(role);
        view.addObject("roleList",roleList);
        view.addObject("provinceList",baseDataService.getProvinces());
    }

    /* 页面 */

    @GetMapping("/index.do")
    @Function("ncode.ncodebatch.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("ncode.ncodebatch.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer batchId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        RightNcodeBatch ncodebatch = ncodebatchService.queryById(batchId);
        view.addObject("ncodebatch", ncodebatch);
		setPageParam(view,request);
		try {
			view.addObject("ncodebatchJson", JacksonUtils.toJsonString(ncodebatch,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("ncode.ncodebatch.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        view.addObject("ncodebatch",new RightNcodeBatch());
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("ncode.ncodebatch.query")
    @ResponseBody
    public JsonResult<PageQuery> list(RightNcodeBatch condtion,HttpServletRequest request)
    {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        ncodebatchService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,RightNcodeBatch ncodebatch,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {
            ncodebatch.setStatus(0);
            ncodebatch.setTenantId(user.getTenantId());
			ncodebatch.setCreatedBy(user.getId().intValue());
			ncodebatch.setCreatedName(user.getName());
			ncodebatch.setCreatedTime(new Date());
			ncodebatch.setUpdatedBy(user.getId().intValue());
			ncodebatch.setUpdatedName(user.getName());
			ncodebatch.setUpdatedTime(new Date());
			ncodebatchService.save(ncodebatch);
		} else {
			ncodebatch.setUpdatedBy(user.getId().intValue());
			ncodebatch.setUpdatedName(user.getName());
			ncodebatch.setUpdatedTime(new Date());
			ncodebatchService.updateTemplate(ncodebatch);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("ncode.ncodebatch.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)RightNcodeBatch ncodebatch,HttpServletRequest request
		)
    {

        return save(true,ncodebatch,request
		);
    }

    @PostMapping("/update.json")
    @Function("ncode.ncodebatch.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  RightNcodeBatch ncodebatch,HttpServletRequest request
		) {
		return save(false,ncodebatch,request
		);
    }



    @GetMapping("/view.json")
    @Function("ncode.ncodebatch.query")
    @ResponseBody
    public JsonResult<RightNcodeBatch>queryInfo(Integer batchId) {
        RightNcodeBatch ncodebatch = ncodebatchService.queryById( batchId);
        return  JsonResult.success(ncodebatch);
    }

    @PostMapping("/delete.json")
    @Function("ncode.ncodebatch.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        ncodebatchService.batchDelRightNcodeBatch(idList);
        return JsonResult.success();
    }

    /**
     * 生成N码
     * @param batchId
     * @param codeName
     * @return
     */
    @PostMapping("/gen.json")
    @Function("ncode.ncodebatch.gen")
    @ResponseBody
    @Transactional
    public JsonResult gen(Integer batchId,String codeName,HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        RightNcodeBatch ncodebatch = new RightNcodeBatch();
        ncodebatch.setBatchId(batchId);
        RightNcodeBatch ncodeBatch = sqlManager.templateOne(ncodebatch);
        String batchIdStr = String.format("%4d", batchId).replace(" ", "0");
        Set<String> set = new HashSet<>();
        List<RightNcodeInsert> list = new ArrayList<>();
        for (int i = 1; i <= ncodeBatch.getNCodeNum(); i++) {
            String codeStr = String.format("%6d", i).replace(" ", "0");
            RightNcodeInsert ncode = new RightNcodeInsert();
            String code = getCode(set);
            set.add(code);
            ncode.setNCode(code);
            ncode.setProvinceId(ncodeBatch.getProvinceId());
            ncode.setCodeName(codeName);
            ncode.setRoleId(ncodeBatch.getRoleId());
            ncode.setNType(ncodeBatch.getNType());
            ncode.setNStatus(0);
            ncode.setTenantId(ncodeBatch.getTenantId());
            ncode.setIsActived(0);
            ncode.setExpiredDate(ncodeBatch.getExpiredDate());
            ncode.setDelStatus(0);
            ncode.setBatchId(batchId);
            ncode.setValidityDay(ncodeBatch.getValidityDay());
            ncode.setRemark(ncodeBatch.getRemark());
            ncode.setNNumber(batchIdStr+codeStr);
            ncode.setCreatedBy(user.getId().intValue());
            ncode.setCreatedName(user.getName());
            ncode.setCreatedTime(new Date());
            list.add(ncode);
            if(list.size()==100){
                sqlManager.insertBatch(RightNcodeInsert.class,list);
                list = new ArrayList<>();
            }
        }
//        for (RightNcode ncode : list) {
//            rightNcodeService.insertNcode(ncode);
//        }
        if(list.size()>0) {
           sqlManager.insertBatch(RightNcodeInsert.class,list);
        }
        ncodebatch.setStatus(1);
        ncodebatch.setUpdatedBy(user.getId().intValue());
        ncodebatch.setUpdatedName(user.getName());
        ncodebatch.setUpdatedTime(new Date());
        ncodebatchService.updateTemplate(ncodebatch);
        return JsonResult.success();
    }

    /**
     * 得到唯一的ncode
     * @param set
     * @return
     */
    public String getCode(Set<String> set) {
        String code = CodeUtils.getCode(10);
        if(rightNcodeService.getRightCountByCode(code)>0){
            return getCode(set);
        }
        if(!set.add(code)){
            return getCode(set);
        }
        return code;
    }

    @GetMapping("/setTime.do")
    @Function("ncode.ncodebatch.setTime")
    @ResponseBody
    public ModelAndView setTime(HttpServletRequest request,Integer batchId) {
        ModelAndView view = new ModelAndView(MODEL+"/setTime.html");
        view.addObject("batchId", batchId);
        return view;
    }

    @PostMapping("/setTime.json")
    @Function("ncode.ncodebatch.setTime")
    @ResponseBody
    public JsonResult setTime(Integer batchId,String date,HttpServletRequest request) throws ParseException {
        if(StringUtils.isEmpty(date)||batchId==null){
            return  JsonResult.failMessage("参数错误！！！");
        }
        CoreUser user = getLoginUser(request);
        Date expiredDate = EDateUtil.parseOtherDate(date,"yyyy-MM-dd");
        RightNcodeBatch ncodeBatch = new RightNcodeBatch();
        ncodeBatch.setBatchId(batchId);
        ncodeBatch.setExpiredDate(expiredDate);
        ncodeBatch.setCreatedBy(user.getId().intValue());
        ncodeBatch.setCreatedName(user.getName());
        ncodeBatch.setCreatedTime(new Date());
        ncodebatchService.updateTemplate(ncodeBatch);
        String remark = user.getName()+"修改过期时间为："+date;
        ncodebatchService.updateNcodeExpiredDateByBatchId(ncodeBatch, remark);

        return JsonResult.success();
    }

}
